//根目录 ../bootstrap/js/
require.config({
    paths : {
        "jquery" : ["http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min","jquery.min"],
        "item" : "item.sku",
        "good" : "good.sku",
        "layer" : "../plugin/layer/layer",
        "verify" : ["https://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min","bootstrapValidator.min"]
    },
    shim: {
        "layer": {
            exports: "layer"
        },
        "verify": {
            exports: "bootstrapValidator"
        }
    }
});
require(["jquery","item"],function($,item){
    var appUrl = $('#_ctx').val();//路径
    //获取当前页面
    var curNum = window.location.search;
    //关闭按钮
    $("button.bot-close").click(function(){
        window.location.href = appUrl+"/outdoor/item/page"+curNum;
    });
    //返回列表
    $(".good-add-suc a").click(function(event){
        event.preventDefault();
        window.location.href = appUrl+"/outdoor/item/page"+curNum;
    });
    //$("#artNumber").val('10' +  (new Date()).valueOf());

    //详情图片删除
    $(".detail-box i").click(function(){
        $(this).parent().remove();
    });

    //商品新增-下拉选择框
    $("select#first").change(function(){
        item.sku.changeTop(this.value);
    });
    $("select#sec").change(function(){
        item.sku.changeSec(this.value);
    });
    $("select#third").change(function(){
        item.sku.changeThird(this.value);
    });
    $("select#four").change(function(){
        $("#categoryId").val($(this).val());
    });
    $("select#selcity").change(function(){
        item.sku.changeBrand(this.value);
    });
    $("select[name='freightTemplateId']").change(function(){
        item.sku.setName(this);
    });

    // //商品新增-图片上传
    // $(".add-input-img input[type='file']").each(function(){
    //     var dataName = $(this).attr("data-image");
    //     $(this).before("<input class='obj-input' type='hidden' name='"+dataName+"' value='' />" +
    //         "<img class='obj-img' src='' style='display:none' />");
    // });
    $("input#banner").change(function(){
        item.uploadImg(this);
    });
    $("input#upimg1").change(function(){
        item.uploadImg(this);
    });
    $(".edit-con input[type='file']").change(function(){
        item.uploadImg(this);
    });
    $("input#detail-image").change(function(){
        item.uploadImg(this,true);
    });
    $(".pro-type-edit").on("change",".edit-con input[type='file']",function(){
        item.uploadImg(this)
    });

    //绑定上传图片事件
    $(".image-text").on("change",".text-box input[type='file']",function(){
        item.uploadImg(this)
    });

    //添加商品描述
    var imageText = $(".image-text");
    var i= 1;
    //添加标签
    var temp = "<div class='btn-box'><input class='addText' type='button' name='addText' value='+ 文字'/>" +
        "<input class='addImg' type='button' name='addImg' value='+ 图片'/><input class='remove' type='button' name='remove' value='X 删除'/></div>"
    $(".image-text .text-box").each(function(){
        $(this).append(temp);
    });
    imageText.prepend("<div class='btn-box'><input class='firstText' type='button' name='firstText' value='+ 文字'/>" +
        "<input class='firstImg' type='button' name='firstImg' value='+ 图片'/></div>")
    var temp1 = "<div class=text-box>" +
        "<textarea name='detailImages["+i+"].path' class=form-control  maxlength='100'></textarea>" +
        "<input class='sort' name='detailImages["+i+"].sort' value='"+i+"' type='hidden'/>" +
        "<input name='detailImages["+i+"].type' value='1' type='hidden'/>"+temp+"</div>";
    var temp2 = "<div class='text-box'><div class='upload-box'>" +
        "<input class='obj-input' type='hidden' name='detailImages["+i+"].path' value='' />" +
        "<img class='obj-img' src='' style='display: none' /><span class='input-file'>" +
        "<input onchange='uploadImg(this)' data-action='goods' data-image='detailImages["+i+"].path' type=file class='no text field'></span>" +
        "<input class='sort' name='detailImages["+i+"].sort' value='"+i+"' type='hidden'/>" +
        "<input name='detailImages["+i+"].type' value='2' type='hidden'/></div>"+temp+"</div>";
    //添加文字
    imageText.on("click",".text-box .addText",function(){
        var _this = $(this);
        var curTr = _this.parents(".text-box");
        curTr.after(temp1);
        sortNumber();
    });
    //添加图片
    imageText.on("click",".text-box .addImg",function(){
        var _this = $(this);
        var curTr = _this.parents(".text-box");
        curTr.after(temp2);
        sortNumber();
    });
    imageText.on("click",".firstText",function(){
        var _this = $(this);
        var curTr = _this.parent();
        curTr.after(temp1);
        sortNumber();
    });
    imageText.on("click",".firstImg",function(){
        var _this = $(this);
        var curTr = _this.parent();
        curTr.after(temp2);
        sortNumber();
    });
    //删除
    imageText.on("click",".text-box .remove",function(){
        var _this = $(this);
        var curTr = _this.parents(".text-box");
        curTr.remove();
        sortNumber();
    });

    //计算下标
    function sortNumber(){
        var liBox = $(".image-text .text-box");
        var index = 0;
        var tArea,dataImg;
        var reg = /\d{1,3}/g;
        liBox.each(function(){
            index = $(this).index() - 1;
            $(this).attr("data-id",index);
            $(this).find("input").not("input[type='file']").each(function(){
                tArea = $(this).siblings("textarea");
                if(tArea.length > 0){
                    tArea.attr("name",tArea.attr("name").replace(reg,index));
                }
                $(this).attr("name",$(this).attr("name").replace(reg,index));
                $(this).siblings(".sort").val(index);
            });
            dataImg = $(this).find("input[type='file']").attr("data-image");
            dataImg && $(this).find("input[type='file']").attr("data-image",dataImg.replace(reg,index));
        });
    }

    //删除
    function removeBox(){
        $(".min1").off("click").click(function(){
            var _this = $(this);
            _this.parent().remove();
            sortNumber();
        });
    }
    removeBox();
    sortNumber();

    //商品详情/编辑
    if($("#id").val()){
        (function() {

            //编辑页面上传图片的点击按钮
            var $edit = $(".input-file-edit");
            $edit.each(function(){
                var $w = $(this).siblings("img.obj-img").width();
                var $h = $(this).siblings("img.obj-img").height();
                $(this).width($w).height($h).find("input[type='file']").width($w).height($h);
            });

            //编辑页分类
            item.sku.changeTop($("#level_1").val());
            item.sku.changeSec($("#level_2").val());
            item.sku.changeThird($("#level_3").val());

            //详情规格
            //获取该商品规格
            var curSpec = [];
            var smallArr = [];
            $(".spec-hide ul").each(function () {
                smallArr = $(this).find("li").text().split(",");
                //清除数组中的空元素
                for (var i = 0; i < smallArr.length; i++) {
                    if (smallArr[i] == "" || typeof(smallArr[i]) == "undefined") {
                        smallArr.splice(i, 1);
                        i = i - 1;
                    }
                }
                curSpec.push(smallArr);
            });
            //curSpec = [["蓝色","M"],["M","L"]]
            //console.log(curSpec)
            //获取所有规格
            var spid = $("#attr-select").val();
            var totalSpec = [];
            $.ajax({
                type: "get",
                url: appUrl + '/item/spec/section/' + spid,
                data: {},
                dataType: 'json',
                success: function (data) {
                    var li = "";
                    var i = k = 0;
                    var name = "";
                    for (var j in data) {
                        //判断是否存在
                        totalSpec = curSpec[k] || [];
                        li += "<ul class=Father_Title><li data-tit='" + data[j].id + "'>" + data[j].name + "</li></ul><ul class='Father_Item"+k+"'>";
                        name = data[j].name;
                        for (var o in data[j].values) {
                            //判断是否在数组中
                            if (totalSpec.indexOf(data[j].values[o].name) != "-1") {
                                li += "<li class=li_width><label><input type='hidden'  value='" + name + "' />"
                                    + "<input type=checkbox id='Checkbox" + i + "' class=chcBox_Width value='" + data[j].values[o].name + "' data-id='" + data[j].values[o].id + "' checked />" + data[j].values[o].name + "<span class=li_empty></span> </label></li>";
                            }
                            else {
                                li += "<li class=li_width><label><input type='hidden'  value='" + name + "' />"
                                    + "<input type=checkbox id='Checkbox" + i + "' class=chcBox_Width value='" + data[j].values[o].name + "' data-id='" + data[j].values[o].id + "' />" + data[j].values[o].name + "<span class=li_empty></span> </label></li>";
                            }
                            i++;
                        }
                        li += "</ul>";
                        k++;
                    }

                    $("#spec").html(li);
                    //详情页禁掉input
                    $(".detail-spec input").each(function(){
                        $(this).prop("disabled","true")
                    });
                },
                error: function () {
                    console.log("请求失败")
                }
            }).done(function () {
                //新规格数组
                require(["good"],function(good){
                    good.Good_sku();
                });

                var newSpec = item.arrChange(curSpec);
                //console.log(newSpec);//["蓝色,M","蓝色,L","红色,M","红色,L"]
                //获取总tr数量
                var trNum = $(".sku-show").length;
                for (var n = 0; n < trNum; n++) {
                    var trHtml = "";
                    var trVal = newSpec[n].split(",");
                    for (var m = 0, len = trVal.length; m < len; m++) {
                        trHtml += "<td>" + trVal[m] + "</td>"
                    }
                    $("tr.sku-show").eq(n).prepend(trHtml);
                }
            });

            //维护成功
            var editSub = $("#submit");
            editSub.click(function () {
                //sku货号
                $(".l-number").each(function(){
                    var i = $(this).parent().parent().index();
                    if($.trim($(this).val()).length < 10){
                        $(this).val('10' + (new Date()).valueOf() + i)
                    }
                });
                //点击提交进行验证
                var bsVal = $("#myForm").data('bootstrapValidator');
                bsVal.validate();
                if(bsVal.isValid()) {
                    require(["layer"], function (layer) {
                        //配置要加载的layer css
                        layer.config({
                            extend: '../plugin/layer/skin/layer.css'
                        });
                        var formdata = $("#myForm").serialize();
                        submitForm(formdata, $("#id").val());
                    });
                }
                else{
                    var smallTop = $("small:visible").eq(0).offset().top - 50;
                    $("html,body").animate({scrollTop:smallTop},300);
                }

            });
            function submitForm(obj, id) {
                $.ajax({
                    type: 'PUT',
                    url: appUrl+'/outdoor/item/' + id,
                    data: obj,
                    dataType: "json",
                    beforeSend:function(){
                        editSub.prop("disabled","true");
                    },
                    success: function (data) {
                        if (data.code == '0') {
                            layer.open({
                                type: 1,
                                title: false,
                                content: $(".good-add-suc"),
                                area: ['600px', '300px'],
                                time: 5000,
                                end: function () {
                                    parent.layer.closeAll();
                                    window.location.href = appUrl+'/outdoor/item/page'+curNum;
                                }
                            });
                        } else {
                            layer.alert(data.desc, {
                                icon: 5
                            });
                        }
                    },
                    complete:function(){
                        editSub.removeAttr("disabled");
                        // $("input[name='token']").prop("disabled","true");
                        refreshToken();
                    },
                    error: function () {
                        layer.alert('系统错误', {
                            icon: 5
                        });
                    }
                });
            }

            function refreshToken() {
                $("input[name='token']").prop("disabled","true");
                // $.ajax({
                //     type: 'get',
                //     url: appUrl + '/refresh/token',
                //     dataType: 'json',
                //     success: function (data) {
                //         if (data.code == '0') {
                //             $("input[name='token']").val(data.result);
                //         } else {
                //             $("input[name='token']").prop("disabled","true");
                //         }
                //     }
                // });
            }

        })();
    }

    //商品新增
    (function(){
        //是否上架 改变value
        var $sto = $(".stores input");
        var $sval = 0;
        $sto.change(function(){
           if($(this).is(":checked")){
               $(this).siblings("input[name='marketAble']").val("1")
               $(this).siblings("input[name='market']").val("1")
           }
           else{
               $(this).siblings("input[name='marketAble']").val("0")
               $(this).siblings("input[name='market']").val("0")
           }
        });

        //商品規格
        $("#attr-select").change(function(){
            var sort = 1;
            var id = $(this).val();
            var itemEdit = $(".pro-type-edit");
            $("#createTable").html("");//初始值
            $(".edit-con").remove();
            $(".arg-box").show();
            itemEdit.hide();
            $.ajax({
                type:"get",
                url:appUrl+'/item/spec/section/'+id,
                data:{},
                dataType:'json',
                success:function (data){
                    var li = "";
                    var i = k = 0;
                    var name = '';
                    for(var j in data){
                        li += "<ul class=Father_Title><li data-tit='"+data[j].id+"'>"+data[j].name+"</li></ul><ul class=Father_Item"+k+">";
                        name = data[j].name;
                        for(var o in data[j].values){
                            li += "<li class=li_width><label><input type='hidden'  value='"+ name +"' />"
                                + "<input type=checkbox id='Checkbox"+i+"' class=chcBox_Width value='"+data[j].values[o].name+"' data-id='"+data[j].values[o].id+"' />"+data[j].values[o].name+"<span class=li_empty></span> </label></li>";
                            i++;
                        }
                        li +=  "</ul>";
                        k++;
                    }
                    $("#spec").html(li);

                    $("#type-id").val(id);
                    $("#type-name").val($("#typeName_"+id).html());
                },
                error:function(){
                    console.log("请求失败")
                }
            }).done(function(){
                //input change 才引用good
                require(["good"],function(good){
                    good.Good_sku();
                });
            });
        });
        //商品屬性
        $("#attr-select").change(function(){
            var id = $(this).val();
            $.ajax({
                type:"get",
                url:appUrl+'/item/attr/section/'+id,
                data:{},
                dataType:'json',
                success:function (data){
                    var li = "";
                    var i = 0;
                    for(var o in data){
                        li += '<li><span>'+ data[o].name +'：</span><input type="text"  name="attrs['+ i +'].value" maxlength="5">'
                            + '<input type="hidden" name="attrs['+ i +'].id" value="'+ data[o].id +'"/>'
                            +'<input type="hidden" name="attrs[' + i + '].name" value="'+data[o].name+'"/></li>';
                        i++
                    }
                    $("#itemAttr").html(li);
                    $("#type-id").val(id);
                    $("#type-name").val($("#typeName_"+id).html());
                },
                error:function(){
                    console.log("请求失败")
                }
            });
        });

        //添加成功
        //商品属性弹窗的关闭按钮
        $(".good-add-attr li .close-btn").click(function () {
            parent.layer.closeAll();
        });
        var addSub = $("#add-submit");
        addSub.click(function () {
            //sku货号
            $(".l-number").each(function(){
                var i = $(this).parent().parent().index();
                if($.trim($(this).val()).length < 10){
                    $(this).val('10' + (new Date()).valueOf() + i)
                }
            });
            //点击提交进行验证
            //$('#myForm').bootstrapValidator('validate');
            var bsVal = $("#myForm").data('bootstrapValidator');
            bsVal.validate();
            if(bsVal.isValid()){
                //提交时加载layer
                require(["layer"],function(layer){
                    // //配置要加载的layer css
                    // layer.config({
                    //     extend: '../plugin/layer/skin/layer.css'
                    // });
                    var formdata = $("#myForm").serialize();
                    //判断货号是否为空
                    if($.trim($("#artNumber").val()) == ""){
                        $("#artNumber").val('10' +  (new Date()).valueOf())
                    }
                    addSubmit(formdata);
                });
            }
            else{
                var smallTop = $("small:visible").eq(0).offset().top - 50;
                $("html,body").animate({scrollTop:smallTop},300);
            }

        });
        function addSubmit(obj) {
            $.ajax({
                method: 'POST',
                url: appUrl+'/outdoor/item/add',
                data: obj,
                dataType: 'json',
                beforeSend:function(){
                    addSub.prop("disabled","true");
                },
                success: function (data) {
                    if (data.code == '0') {
                        layer.open({
                            type: 1,
                            title: false,
                            content: $(".good-add-suc"),
                            area: ['600px', '300px'],
                            time: 5000,
                            end: function () {
                                parent.layer.closeAll();
                                window.location.href = appUrl+'/outdoor/item/page';
                            }
                        });
                    } else {
                        layer.alert(data.desc, {
                            icon: 5
                        });
                    }
                },
                complete:function(){
                    addSub.removeAttr("disabled");
                    $("input[name='token']").prop("disabled","true");
                },
                error: function () {
                    layer.alert('请求失败', {
                        icon: 5
                    });
                }
            });
        }
    })();

    //表单验证
    require(["verify"],function(bootstrapValidator) {
        var regPrice = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
        var regNumber = /(^[1-9]\d*$)|(^0$)/;
        $('#myForm').bootstrapValidator({
            fields: {
                first: {
                    validators: {
                        notEmpty: {
                            message: '请选择分类'
                        }
                    }
                },
                shopId:{
                    validators: {
                        notEmpty: {
                            message: '请选择商户'
                        }
                    }
                },
                artNumber: {
                    validators: {
                        stringLength: {
                            min: 10,
                            max: 20,
                            message: '商品货号必须大于10，小于20位数字'
                        },
                        regexp: {
                            regexp: regNumber,
                            message: '商品货号只能是整数'
                        }
                    }
                },
                name: {
                    validators: {
                        notEmpty: {
                            message: '商品名称不能为空'
                        }
                    }
                },
                credits: {
                    validators: {
                        regexp: {
                            regexp: regNumber,
                            message: '龙珠价格必须是整数'
                        }
                    }
                },
                price: {
                    validators: {
                        notEmpty: {
                            message: '商品售价不能为空'
                        },
                        regexp: {
                            regexp: regPrice,
                            message: '价格必须是数字、且最多保留两位小数'
                        }
                    }
                },
                oriPrice: {
                    validators: {
                        regexp: {
                            regexp: regPrice,
                            message: '商品原价必须是数字、且最多保留两位小数'
                        }
                    }
                },
                singlePiece: {
                    validators: {
                        notEmpty: {
                            message: '商品重量不能为空'
                        },
                        regexp: {
                            regexp: regPrice,
                            message: '商品重量必须是数字、且最多保留两位小数'
                        }
                    }
                },
                stock: {
                    validators: {
                        notEmpty: {
                            message: '商品库存不能为空'
                        },
                        regexp: {
                            regexp: regPrice,
                            message: '商品库存必须是数字、且最多保留两位小数'
                        }
                    }
                },
                stockWarn: {
                    validators: {
                        regexp: {
                            regexp: regPrice,
                            message: '商品预警值必须是数字、且最多保留两位小数'
                        }
                    }
                },
                spprice: {
                    validators: {
                        notEmpty: {
                            message: '请选择一种运费'
                        }
                    }
                },
                brand: {
                    validators: {
                        notEmpty: {
                            message: '请至少选择一种经营品牌'
                        }
                    }
                }
            }
        });
    });
});


